package com.lm.ip2region.util;

import org.lionsoul.ip2region.xdb.Searcher;

import java.net.URL;
import java.util.Objects;

public class Ip2RegionUtil {
    private static final String DB_PATH = "xdb/ip2region.xdb";
    private static Searcher searcher ;
    static {
        try {
            URL url = Ip2RegionUtil.class.getClassLoader().getResource(DB_PATH);

            byte[] vIndex = Searcher.loadVectorIndexFromFile(url.getPath());
            searcher = Searcher.newWithVectorIndex(url.getPath(), vIndex);
        } catch (Exception e) {
            throw new RuntimeException("Failed to initialize Ip2Region", e);
        }
    }

    public static String  getRegion(String ip,boolean format) {
        try {
            String region = searcher.search(ip);
            if (format){
                return region;
            }
            String[] split = region.split("\\|");
            String s = split[0] + split[2] + split[3];
            return s;
        } catch (Exception e) {
            throw new RuntimeException("Failed to get region", e);
        }
    }

    public static void close() {
        try {
            if(Objects.nonNull(searcher)){
                searcher.close();
            }
        }catch (Exception e){
            throw new RuntimeException("Failed to close ", e);
        }
    }

}
